//数字输入框的antd封装

import React,{Component} from 'react'
import {Input,Tooltip } from 'antd'


function formatNumber(value) {
  value += '';
  const list = value.split('.');
  const prefix = list[0].charAt(0) === '-' ? '-' : '';
  let num = prefix ? list[0].slice(1) : list[0];
  let result = '';
  while (num.length > 3) {
    result = `,${num.slice(-3)}${result}`;
    num = num.slice(0, num.length - 3);
  }
  if (num) {
    result = num + result;
  }
  return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`;
}

class NumberInput extends Component {
 
  onChange = (e) => {
    const { value } = e.target;
    if(this.props.type){
      const reg = /^(0(\.\d{0,2})?|[1-9]\d?(\.\d{0,2})?|100)$/           //正则判断为数字，并且小数点只有两位，并且小于等于100
      if ((!isNaN(value) && reg.test(value)) || value === '' || value === '-') {
        this.props.onChange(value);
      }
    }else{
      const reg = /^\d+(\.\d{0,2})?$/     //正则判断为数字，并且小数点后只有两位
      if ((!isNaN(value) && reg.test(value)) || value === '' || value === '-') {
        this.props.onChange(value);
      }
    }
  }

  render(){
    const { value } = this.props;
    const title = value ? (
      <span className="numeric-input-title">
        {value !== '-' ? formatNumber(value) : '-'}
      </span>
    ) : 'Input a number';

    return (
      <Tooltip 
        trigger={['focus']}
        title={title}
        placement="topLeft"
        overlayClassName="numeric-input"
      >  
        <Input
          {...this.props}
          onChange={this.onChange}
          placeholder={this.props.placeholder}
          maxLength="25"
        />
      </Tooltip>
    )
  }
}
export default NumberInput


